import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:table_calendar/table_calendar.dart';

class SignInPage extends StatefulWidget {
  @override
  _SignInPageState createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> {
  CalendarFormat _calendarFormat = CalendarFormat.month;
  DateTime _focusedDay = DateTime.now();
  final kFirstDay = DateTime(
      DateTime.now().year - 2, DateTime.now().month, DateTime.now().day);
  final kLastDay = DateTime(
      DateTime.now().year + 2, DateTime.now().month, DateTime.now().day);
  var _signCount = '0';
  var _integral = '0';
  SignInData? _data;
  bool isSign = false;

  var local =
      appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
  // if (local.contains('zh')) {
  @override
  void initState() {
    _getData(isFrist: true);
    DLog(_focusedDay);
    super.initState();
    _focusedDay = DateTime.fromMillisecondsSinceEpoch(
        DateTime.now().millisecondsSinceEpoch - (appContext.timeStamp * 1000));
    // _focusedDay = DateTime.parse(
    // '${DateTime.now().millisecondsSinceEpoch - (appContext.timeStamp * 1000)}');
    //  ??
    // DateTime.now();
    // DLog(_focusedDay);
  }

  void _getData({bool isFrist = false}) async {
    // month
    // DLog(_focusedDay.month.toString().padLeft(2, '0'));
    try {
      _data = await API.shared.user
          .signDetail("${_focusedDay.year}-${_focusedDay.month}");
      _signCount = _data?.sign_day ?? "0";
      _integral = _data?.integral ?? "0";
      if (isFrist) {
        // var isSign = false;
        var month = '';
        var day = _focusedDay.day.toString();
        if (_focusedDay.month < 10) {
          month = '0${_focusedDay.month}';
        } else {
          month = _focusedDay.month.toString();
        }
        if (_focusedDay.day < 10) {
          day = '0${_focusedDay.day}';
        } else {
          day = _focusedDay.day.toString();
        }
        var currentTime = "${_focusedDay.year}-${month}-${day}";
        if (_data != null) {
          var list = _data?.sign_data ?? [];
          for (var item in list) {
            if (item.day == currentTime) {
              // isSign = item.status;
              isSign = item.status;
            }
          }
        }
      }
      setState(() {});
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowToast(e.message);
      // } else {
      //   customShowToast(S.of(context).network_error);
      // }
    }
  }

  void _sign() async {
    Future<void> _request() async {
      await API.shared.user.sign();
    }

    // try {
    // int count = DateTime.now().millisecondsSinceEpoch;
    await loading(_request, text: S.of(context).loading);

    // DLog(DateTime.now().millisecondsSinceEpoch - count);
    // count = DateTime.now().millisecondsSinceEpoch;
    _getData();
    customShowToast(S().sign_success);
    if (mounted) {
      setState(() {
        isSign = true;
      });
    }
    // ''.padLeft(1, '0');
    // _getData();
    // DLog(DateTime.now().millisecondsSinceEpoch - count);
    // } catch (e) {
    // await UtilsOther.showCustomShowError(e);
    // if (e is DioError) {

    //   customShowToast(e.message);
    // } else {
    //   customShowToast(S.of(context).network_error);
    // }
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(S.current.sign_in),
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.only(bottom: 20),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15),
            decoration: BoxDecoration(
                color: Color(0xffF7F7F7),
                image: DecorationImage(
                    alignment: Alignment.topCenter,
                    image: AssetImage(
                      local.contains('zh')
                          ? 'assets/images/sign_in_bg.png'
                          : 'assets/images/sign_in_bg_en.png',
                    ))),
            child: Column(
              children: [
                Row(),
                SizedBox(
                  width: 1.sw,
                  height: 120.w,
                ),
                Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(12)),
                      color: Colors.white),
                  height: 82,
                  padding: EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              RichText(
                                textAlign: TextAlign.left,
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: S().sign_info_left + ' ',
                                      style: (TextStyle(
                                        fontWeight: FontWeight.w400,
                                        fontFamily: 'PingFang SC',
                                        fontSize: 14,
                                        color: Color(0xff333333),
                                      )),
                                    ),
                                    TextSpan(
                                      text: _signCount,
                                      style: (TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontFamily: 'PingFang SC',
                                        fontSize: 32,
                                        color: Color(0xffE94135),
                                      )),
                                    ),
                                    TextSpan(
                                      text: ' ' + S().sign_info_right,
                                      style: (TextStyle(
                                        fontWeight: FontWeight.w400,
                                        fontFamily: 'PingFang SC',
                                        fontSize: 14,
                                        color: Color(0xff333333),
                                      )),
                                    ),
                                  ],
                                ),
                              ),
                              Text(
                                // S().sign_mypoint
                                '${S().sign_mypoint}$_integral',
                                style: TextStyle(
                                  fontWeight: FontWeight.w400,
                                  color: Color(0xff999999),
                                  fontSize: 12,
                                  fontFamily: 'PingFang SC',
                                ),
                              ),
                              SizedBox(height: 8)
                            ],
                          )
                        ],
                      ),
                      _signBtn(),
                    ],
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(12)),
                    color: Colors.white,
                  ),
                  padding: EdgeInsets.only(bottom: 10, top: 10),
                  child: TableCalendar(
                    calendarBuilders:
                        CalendarBuilders(selectedBuilder: (ctx, day1, day2) {
                      // 选中
                      return Center(
                        child: Container(
                          width: 33,
                          height: 33,
                          decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(16.5)),
                            color: ThemeColor.primaryColor,
                          ),
                          child: Center(
                            child: Text('${day1.day}'),
                          ),
                        ),
                      );
                    }, todayBuilder: (ctx, day1, day2) {
                      //当天
                      return Stack(
                        children: [
                          Center(
                            child: Container(
                              width: 33,
                              height: 33,
                              decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(16.5)),
                                color: _checkStatus(day1)
                                    ? ThemeColor.primaryColor
                                    : Colors.white,
                              ),
                              child: Center(
                                child: Text('${day1.day}'),
                              ),
                            ),
                          ),
                          Positioned(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  height: 4,
                                  width: 4,
                                  decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(2)),
                                    color: Color(0xffFF7E0B),
                                  ),
                                )
                              ],
                            ),
                            right: 0,
                            left: 0,
                            bottom: 7,
                          ),
                        ],
                      );
                    }, defaultBuilder: (ctx, day1, day2) {
                      //这是非当天，非选中的普通状态
                      return Stack(
                        children: [
                          Center(
                            child: Container(
                              width: 33,
                              height: 33,
                              decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(16.5)),
                                color: _checkStatus(day1)
                                    ? ThemeColor.primaryColor
                                    : Colors.white,
                              ),
                              child: Center(
                                child: Text('${day1.day}'),
                              ),
                            ),
                          ),
                        ],
                      );
                    }),
                    headerStyle: HeaderStyle(
                      formatButtonVisible: false,
                      titleCentered: true,
                      leftChevronVisible: false,
                      rightChevronVisible: false,
                      // leftChevronMargin: EdgeInsets.zero,
                      // leftChevronPadding: EdgeInsets.zero,
                      // leftChevronIcon: Container(
                      //   width: ScreenAdapter.screenW()/2-75,
                      //   height: 40,
                      //   alignment: Alignment.centerRight,
                      //   child: Icon(Icons.chevron_left),
                      // ),
                      // rightChevronMargin: EdgeInsets.zero,
                      // rightChevronPadding: EdgeInsets.zero,
                      // rightChevronIcon: Container(
                      //   width: ScreenAdapter.screenW()/2-75,
                      //   height: 40,
                      //   alignment: Alignment.centerLeft,
                      //   child: Icon(Icons.chevron_right),
                      // ),
                    ),
                    // availableGestures: AvailableGestures.none,
                    firstDay: kFirstDay,
                    lastDay: kLastDay,
                    focusedDay: _focusedDay,
                    calendarFormat: _calendarFormat,
                    daysOfWeekHeight: 30,
                    rowHeight: 40,
                    // selectedDayPredicate: (day) {
                    //   return isSameDay(_selectedDay, day);
                    // },
                    // onDaySelected: (selectedDay, focusedDay) {
                    //   if (!isSameDay(_selectedDay, selectedDay)) {
                    //     setState(() {
                    //       _selectedDay = selectedDay;
                    //       _focusedDay = focusedDay;
                    //     });
                    //   }
                    // },
                    onFormatChanged: (format) {
                      if (_calendarFormat != format) {
                        setState(() {
                          _calendarFormat = format;
                        });
                      }
                    },
                    onPageChanged: (focusedDay) {
                      _focusedDay = focusedDay;
                      DLog(focusedDay);
                      _getData();
                    },
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  // height: 104,
                  width: double.infinity,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(12)),
                      color: Colors.white),
                  padding: EdgeInsets.all(15),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        S().sign_info,
                        style: TextStyle(
                          fontFamily: 'PingFang SC',
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: Colors.black,
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        '${S().sign_info1(_data?.signIntegral ?? '')}\n${S().sign_info2(_data?.signIntegralExtra ?? '')}\n${S().sign_info3}',
                        style: TextStyle(
                          fontFamily: 'PingFang SC',
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          color: Colors.black.withOpacity(0.6),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  bool _checkStatus(DateTime date) {
    var month = '';
    var day = date.day.toString();
    if (date.month < 10) {
      month = '0${date.month}';
    } else {
      month = date.month.toString();
    }
    if (date.day < 10) {
      day = '0${date.day}';
    } else {
      day = date.day.toString();
    }
    var zhTime = "${date.year}-$month-$day";
    if (_data != null) {
      var list = _data?.sign_data ?? [];
      for (var item in list) {
        if (item.day == zhTime) {
          return item.status;
        }
      }
    }
    return false;
  }

  Widget _signBtn() {
    return Container(
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: ClickUtils.debounce(() {
          if (!isSign) {
            _sign();
          }
        }),
        child: Container(
          // width: 80,
          height: 36,
          padding: EdgeInsets.symmetric(horizontal: 10),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: isSign ? Color(0xffEEEEEE) : ThemeColor.primaryColor,
            borderRadius: BorderRadius.all(Radius.circular(4)),
          ),
          child: Text(
            isSign ? S().sign_sign : S().sign_notsign,
            style: TextStyle(
              fontSize: 14,
              color: isSign ? Colors.black.withOpacity(0.4) : Colors.black,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }
}

class SignInData {
  late String integral;
  late String sign_day;
  late String signIntegral;
  late String signIntegralExtra;
  late List<SignInItem> sign_data;
  SignInData(Map<String, dynamic> json) {
    integral = "${json["integral"]}";
    sign_day = "${json["sign_day"]}";
    signIntegral = "${json['sign_integral']}";
    signIntegralExtra = "${json['sign_integral_extra']}";

    try {
      var list = json["sign_data"] as List<dynamic>;
      sign_data = list.map((e) => SignInItem(e)).toList();
    } catch (e) {
      sign_data = [];
    }
  }
}

class SignInItem {
  late String day;
  late bool status;

  SignInItem(Map<String, dynamic> json) {
    day = "${json["day"]}";
    try {
      status = json["status"] as bool;
    } catch (e) {
      status = false;
    }
  }
}
